#!/usr/bin/env python
#
#       Socket.py
#       
#       Copyright 2009 Ben Davis <its.hip@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import pickle
import socket
import threading
import time
import zlib

class Server(threading.Thread):
    """Wrapper around the socket object which automatically handles
    pickling and compression"""
    def __init__(self, addr):
        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.settimeout(3)
        self.addr = addr
        self.queue = []
        self.lock = threading.Lock()
        self.stop = False
        self.disconnected = False
        self.connected = False
        
    def send(self, data, *args):
        self.socket.send(zlib.compress(pickle.dumps(data), 9))

    def recv(self):
        data = ""
        while True:
            try:
                # Try to grab part of a packet from the server
                recv = self.socket.recv(1024)
                # If server disconnected
                if recv == '':
                    return None
                # Add part to data
                data += recv
                if len(recv) < 1024:
                    # Finished receiving data
                    raise socket.timeout
            except socket.timeout:
                # If socket timed out and we have data
                if len(data) > 0:
                    # Decompress, unpickle and return
                    try:
                        return pickle.loads(zlib.decompress(data))
                    except zlib.error:
                        pass
                # If socket timed out and we didn't receive any data
                else:
                    return False
        
    def join(self):
        self.stop = True
        threading.Thread.join(self)

    def run(self):
        try:
            # Connect to the server
            self.socket.connect(self.addr)
        except socket.error, e:
            self.connected = e
        else:
            self.connected = True
            while not self.stop and not self.disconnected:
                # Get the new data from server
                data = self.recv()
                if data is None:
                    # Server disconnected; act appropriately
                    # At the moment we just exit
                    self.disconnected = True
                elif data:
                    self.lock.acquire()
                    self.queue.append(data)
                    self.lock.release()
            if not self.disconnected:
                self.socket.close()
    
    def get(self):
        """Get (and clear) the list of packets"""
        self.lock.acquire()
        r = self.queue[:]
        self.queue = []
        self.lock.release()
        return r
        
    def poll(self):
        """Get (and clear) the first packet in the queue"""
        if len(self.queue) > 0:
            self.lock.acquire()
            r = self.queue.pop(0)
            self.lock.release()
            return r
    
    def wait(self):
        """Wait until a new packet arrives and get it"""
        r = None
        while r is None:
            r = self.poll()
            time.sleep(0.001)
        return r
